package com.ry.demo.register.server;

import java.util.Map;

/**
 * @Author: lihui
 * @Date: 2021-12-01 13:33
 * @Description:
 */
public class ServiceAliveMonitor {

    /**
     * 检查服务实例是否存活的间隔
     */
    private static final Long CHECK_ALIVE_INTERVAL = 60 * 1000L;

    /**
     * 启动心跳检查后台线程
     */
    public void start() {
        Daemon daemon = new Daemon();
        daemon.setDaemon(true);
        daemon.start();
    }

    private class Daemon extends Thread {

        private Registry registry = Registry.getInstance();

        @Override
        public void run() {

            while (true){
                try {

                    Map<String, Map<String, ServiceInstance>> registryMap = this.registry.getRegistry();

                    for (String serviceName : registryMap.keySet()){

                        Map<String, ServiceInstance> serviceInstanceMap = registryMap.get(serviceName);

                        for (ServiceInstance serviceInstance : serviceInstanceMap.values()){

                            // 如果该服务实例距离上一次发送心跳已经超过90秒了，就认为该服务实例故障了
                            // 从注册表中摘除这个故障的服务实例
                            if (!serviceInstance.isAlive()){
                                registry.removeInstance(serviceName,serviceInstance.getServiceInstanceId());
                            }
                        }
                    }

                    // 每隔60秒进行一次心跳检查
                    Thread.sleep(CHECK_ALIVE_INTERVAL);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }


        }
    }

}
